package com.mrjoew.weekend.entities;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;

/**
 * @author Christopher Jones
 * @explain 返回数据格式
 * @date 2019/3/17 0017 1:27
 */
@Data
public class Response<T> {

    /**
     * 状态码: 成功
     */
    public static final int SUCCESS = 200;

    /**
     * 状态码: 异常
     */
    public static final int ERROR = -1;

    /**
     * 状态码: 校验异常
     */
    public static final int ERROR_VALIDATE = -2;

    /**
     * 静态成功对象
     */
    public static final Response<Object> OK = new Response<>(SUCCESS, null, null);

    /**
     * 静态异常对象
     */
    public static final Response<Object> FAILED = new Response<>(ERROR, null, null);

    /**
     * 数据
     */
    private T data;

    /**
     * 状态码
     */
    private int status;

    /**
     * 异常信息
     */
    private Object error;

    public Response(int status, T data, Object error) {
        this.status = status;
        this.data = data;
        this.error = error;
    }

    public static Response<Object> ok() {
        return new Response<>(SUCCESS, null, null);
    }

    /**
     * 成功返回
     *
     * @param data 返回数据
     * @return Response
     */
    public static Response<Object> ok(Object data) {
        return new Response<>(SUCCESS, data, null);
    }

    /**
     * 异常返回
     *
     * @param error 异常信息
     * @return Response
     */
    public static Response<Object> error(String error) {
        return new Response<>(ERROR, null, error);
    }

    /**
     * 自定义返回码类型
     *
     * @param code  异常码
     * @param error 异常信息
     * @return Response
     */
    public static Response<Object> error(int code, String error) {
        return new Response<>(code, null, error);
    }

    /**
     * 自定义返回码类型
     *
     * @param code  异常码
     * @param error 异常数据
     * @return Response
     */
    public static Response<Object> error(int code, Object error) {
        return new Response<>(code, error, null);
    }

    public String json() {
        return JSONObject.toJSONString(this);
    }
}
